import { getQuestions } from '../../api/exam.js'

const state = {
    exmpntOrTitle: "考点练习",
    questionsData: [],
    questionIndex: 0, //当前题号
    pageSize: 10,
    ansArr: [],
    rightAns: 0
}

const mutations = {
    // 获取试题
    SET_QUESTIONS(state, data) {
        // console.log(data.data.data)
        state.questionsData = data
    },
    // 上下题、题号按钮
    SET_QUESINDEX(state, upDown) {
        // console.log(upDown)
        if (upDown == "-") { // 上一题
            state.questionIndex--
            if (state.questionIndex < 0) {
                state.questionIndex = 0
            }
        } else if (upDown == "+") { // 下一题
            state.questionIndex++
            if (state.questionIndex > state.questionsData.length - 1) {
                state.questionIndex = state.questionsData.length - 1
            }
        } else { // 题号按钮
            state.questionIndex = upDown
        }
    },
    // 选项
    SET_ANSWER(state, checkboxArr) {
        state.ansArr = checkboxArr.sort()
        // console.log(state.ansArr)
        if (state.ansArr.length) {
            state.questionsData[state.questionIndex]['ans'] = state.ansArr
        }
        console.log(state.questionsData)
    },
    // 弹框内容
    SET_RIGHT(state, num) {
        state.rightAns = num
    },
    // 头部导航栏标题
    SET_TITLE(state, title) {
        state.exmpntOrTitle = title
    }
}

const actions = {
    // 获取试题
    async getQuestions({ state, commit }, place) {
        console.log(place)
        if (place == "point") {
            let data = await getQuestions({ pageSize: state.pageSize })
            commit('SET_QUESTIONS', data.data.data.data)
            commit('SET_TITLE', "考点练习")
        } else {
            let mistakesArr = JSON.parse(localStorage.getItem('appMistakes') || '[]')
            console.log(mistakesArr)
            if (mistakesArr.length > 90) {
                mistakesArr = mistakesArr.splice(0, 90)
            }
            if(mistakesArr==[]) {

            }else{
                commit('SET_QUESTIONS', mistakesArr)
                commit('SET_TITLE', "错题练习")
            }
        }
    }
}

const getters = {
    // 每页试题
    questionItem(state) {
        return state.questionsData[0] && state.questionsData[state.questionIndex];
    },
    // 每页选项
    questionOptions(state, getters) {
        let arr = getters.questionItem ? JSON.parse(getters.questionItem.options) : [];
        for (var i = 0; i < arr.length; i++) {
            const item = arr[i];
        }
        return arr;
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters
}